package com.ethan.blog.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.ethan.blog.common.properties.JwtProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class JwtUtil {

    private static JwtProperties jwtProperties = null;

    @Autowired
    private JwtUtil(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    /**
     * 生成 JWT Token
     *
     * @param claims 业务数据
     * @return 生成的 token 字符串
     */
    public static String generateToken(Map<String, Object> claims) {
        log.info("Generating JWT Token with claims: {}", claims);
        return JWT.create()
                .withClaim(jwtProperties.getClaimsName(), claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpireTime()))
                .sign(Algorithm.HMAC256(jwtProperties.getUserSecretKey()));
    }

    /**
     * 解析并验证 JWT Token
     *
     * @param token 待验证的 token 字符串
     * @return 从 token 中解析出的业务数据
     * @throws JWTVerificationException 验证失败时抛出该异常
     */
    public static Map<String, Object> parseToken(String token) {
        log.info("Parsing JWT Token: {}", token);
        return JWT.require(Algorithm.HMAC256(jwtProperties.getUserSecretKey()))
                .build()
                .verify(token)
                .getClaim(jwtProperties.getClaimsName())
                .asMap();
    }
}
